package com.neusoft.elmboot.service.impl;

import java.util.List;

//import com.neusoft.elmboot.mapper.FoodMapper;
import com.neusoft.elmboot.po.Cart;
import com.neusoft.elmboot.po.Food;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.elmboot.mapper.CartMapper;
import com.neusoft.elmboot.mapper.OrderDetailetMapper;
import com.neusoft.elmboot.mapper.OrdersMapper;
import com.neusoft.elmboot.po.OrderDetailet;
import com.neusoft.elmboot.po.Orders;
import com.neusoft.elmboot.po.User;
import com.neusoft.elmboot.service.OrdersService;
import com.neusoft.elmboot.service.UserCouponService;
import com.neusoft.elmboot.service.UserService;

@Service
public class OrdersServiceImpl implements OrdersService{
	
	@Autowired
	private CartMapper cartMapper;
	@Autowired
	private OrdersMapper ordersMapper;
	@Autowired
	private OrderDetailetMapper orderDetailetMapper;
	@Autowired
	private UserCouponService userCouponService;
	@Autowired
	private UserService userService;
	//@Autowired
	//private FoodMapper foodMapper;

	@Override
	@Transactional
	public int createOrders(Orders orders) {
		//1、查询当前用户购物车中当前商家的所有食品
		Cart cart = new Cart();
		cart.setUserId(orders.getUserId());
		cart.setBusinessId(orders.getBusinessId());
		List<Cart> cartList = cartMapper.listCart(cart);

		//2、获取用户信息以获取等级和折扣
		User user = userService.getUserInfoById(orders.getUserId());
		Double couponDiscountAmount = 0.0;
		Double levelDiscountAmount = 0.0;
		Double finalTotal = orders.getOrderTotal();
		
		// 2.1 先应用优惠券折扣（如果有）
		if (orders.getCouponId() != null && orders.getCouponId() > 0) {
			// 验证优惠券
			if (userCouponService.validateCoupon(orders.getCouponId(), orders.getOrderTotal())) {
				// 获取优惠券信息
				com.neusoft.elmboot.po.UserCoupon coupon = userCouponService.getCouponById(orders.getCouponId());
				if (coupon != null) {
					couponDiscountAmount = coupon.getDiscountAmount();
					finalTotal = Math.max(0, finalTotal - couponDiscountAmount);
				}
			}
		}
		
		// 2.2 计算等级折扣（基于优惠券折扣后的价格）
		if (user != null) {
			int userDiscount = user.getDiscount() != null ? user.getDiscount() : 99;
			if (userDiscount < 100) {
				// 等级折扣金额 = 优惠券折扣后的价格 * (100 - 折扣) / 100
				levelDiscountAmount = finalTotal * (100 - userDiscount) / 100.0;
			}
		}
		
		// 2.3 计算最终价格
		finalTotal = Math.max(0, finalTotal - levelDiscountAmount);
		
		orders.setCouponDiscountAmount(couponDiscountAmount);
		orders.setLevelDiscountAmount(levelDiscountAmount);
		orders.setDiscountAmount(couponDiscountAmount + levelDiscountAmount);
		orders.setFinalTotal(finalTotal);

		//3、创建订单（返回生成的订单编号）
//		orders.setOrderDate(CommonUtil.getCurrentDate());
		ordersMapper.saveOrders(orders);
		int orderId = orders.getOrderId();

		//4、批量添加订单明细
		for(Cart c : cartList) {
			Food food = c.getFood();

			OrderDetailet od = new OrderDetailet();
			od.setOrderId(orderId);
			od.setFoodName(food.getFoodName());
			od.setFoodPrice(food.getFoodPrice());
			od.setQuantity(c.getQuantity());

			orderDetailetMapper.saveOrderDetailet(od);
		}

		//5、从购物车表中删除相关食品信息
		cartMapper.removeCart(cart);
		
		//6、标记优惠券为已使用（如果有）
		if (orders.getCouponId() != null && orders.getCouponId() > 0) {
			userCouponService.useCoupon(orders.getCouponId(), orderId);
		}

		return orderId;
	}
	
	@Override
	public Orders getOrdersById(Integer orderId) {
		return ordersMapper.getOrdersById(orderId);
	}
	
	@Override
	public List<Orders> listOrdersByUserId(String userId){
		return ordersMapper.listOrdersByUserId(userId);
	}

	@Override
	public void updateOrderState(Integer state, Integer orderId) {
		ordersMapper.updateOrderState(state, orderId);
	}

	@Override
	public void updateOrderStateWithPaymentType(Integer state, String paymentType, Integer orderId) {
		ordersMapper.updateOrderStateAndPaymentType(state, paymentType, orderId);
	}

	@Override
	public void updateRefundInfo(Integer orderId, Integer refundStatus, String refundReason) {
		ordersMapper.updateRefundInfo(orderId, refundStatus, refundReason);
	}

	@Override
	public List<Orders> listOrdersByBusinessId(String businessId) {
		return ordersMapper.listOrdersByBusinessId(businessId);
	}

	@Override
	public List<OrderDetailet> getOrderDetailetByOrderId(Integer orderId) {
		return ordersMapper.getOrderDetailetByOrderId(orderId);
	}

	@Override
	public void cancelOrder(Integer orderId) {
		ordersMapper.delOrderById(orderId);
		orderDetailetMapper.delOdById(orderId);
	}

	@Override
	public Integer getOrderId(String userId, String businessId, String orderDate) {
		return ordersMapper.getOrderId(userId, businessId, orderDate);
	}
	
	@Override
	@Transactional
	public int createOrdersWithCoupon(Orders orders, Integer couponId) {
		// 获取用户信息以获取等级和折扣
		User user = userService.getUserInfoById(orders.getUserId());
		if (user == null) {
			throw new RuntimeException("用户不存在");
		}
		
		// 查询当前用户购物车中当前商家的所有食品
		Cart cart = new Cart();
		cart.setUserId(orders.getUserId());
		cart.setBusinessId(orders.getBusinessId());
		List<Cart> cartList = cartMapper.listCart(cart);
		
		Double couponDiscountAmount = 0.0;
		Double levelDiscountAmount = 0.0;
		Double finalTotal = orders.getOrderTotal();
		
		// 1. 先应用优惠券折扣
		if (couponId != null && couponId > 0) {
			// 验证优惠券
			if (!userCouponService.validateCoupon(couponId, orders.getOrderTotal())) {
				throw new RuntimeException("优惠券无效或不满足使用条件");
			}
			
			// 获取优惠券信息
			com.neusoft.elmboot.po.UserCoupon coupon = userCouponService.getCouponById(couponId);
			if (coupon != null) {
				couponDiscountAmount = coupon.getDiscountAmount();
				finalTotal = Math.max(0, finalTotal - couponDiscountAmount);
				
				orders.setCouponId(couponId);
			}
		}
		
		// 2. 计算等级折扣（基于优惠券折扣后的价格）
		int userDiscount = user.getDiscount() != null ? user.getDiscount() : 99;
		if (userDiscount < 100) {
			// 等级折扣金额 = 优惠券折扣后的价格 * (100 - 折扣) / 100
			levelDiscountAmount = finalTotal * (100 - userDiscount) / 100.0;
		}
		
		// 3. 计算最终价格
		finalTotal = Math.max(0, finalTotal - levelDiscountAmount);
		
		orders.setCouponDiscountAmount(couponDiscountAmount);
		orders.setLevelDiscountAmount(levelDiscountAmount);
		orders.setDiscountAmount(couponDiscountAmount + levelDiscountAmount);
		orders.setFinalTotal(finalTotal);
		
		// 创建订单（不调用createOrders，直接执行逻辑以保留折扣信息）
		ordersMapper.saveOrders(orders);
		int orderId = orders.getOrderId();
		
		// 批量添加订单明细
		for(Cart c : cartList) {
			Food food = c.getFood();
			
			OrderDetailet od = new OrderDetailet();
			od.setOrderId(orderId);
			od.setFoodName(food.getFoodName());
			od.setFoodPrice(food.getFoodPrice());
			od.setQuantity(c.getQuantity());
			
			orderDetailetMapper.saveOrderDetailet(od);
		}
		
		// 从购物车表中删除相关食品信息
		cartMapper.removeCart(cart);
		
		// 标记优惠券为已使用
		if (couponId != null && couponId > 0) {
			userCouponService.useCoupon(couponId, orderId);
		}
		
		return orderId;
	}

	@Override
	public java.util.Map<String, Object> getTodayOrderStats(String businessId) {
		return ordersMapper.getTodayOrderStats(businessId);
	}

	@Override
	public java.util.Map<String, Object> getMonthlyOrderStats(String businessId) {
		return ordersMapper.getMonthlyOrderStats(businessId);
	}
}
